package com.bolins.webpreview;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bolins.util.WebCapt;

@SuppressWarnings("serial")
public class PreviewWebServlet extends HttpServlet {
	private final static Logger log = LoggerFactory
			.getLogger(PreviewWebServlet.class);

	// 默认网页预览图保存路径
	private final static String DEFAULT_CAPTURE_PATH = "/images/capture/";
	private final static int DEFAULT_WIDTH = 220;
	private final static int DEFAULT_HEIGHT = 190;
	private int width;
	private int height;
	private String capture_path;
	private String realPath;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String url = req.getParameter("url");
		String id = req.getParameter("id");

		String widthStr = req.getParameter("width");
		String heightStr = req.getParameter("height");
		if (StringUtils.isBlank(widthStr)) {
			width = DEFAULT_WIDTH;
		} else {
			width = Integer.parseInt(widthStr);
		}

		if (StringUtils.isBlank(heightStr)) {
			height = DEFAULT_HEIGHT;
		} else {
			height = Integer.parseInt(heightStr);
		}

		String fileName = capture_path + id + ".jpg";

		WebCapt.getWebCapt(url, width, height, realPath + capture_path, id);

		resp.sendRedirect(fileName.substring(1));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		realPath = config.getServletContext().getRealPath("/");
		capture_path = config.getInitParameter("capture_path");
		if (StringUtils.isBlank(capture_path)) {
			capture_path = DEFAULT_CAPTURE_PATH;
		}
	}

	@Override
	public void destroy() {
		capture_path = null;
	}

}
